<template>
  <div>
    <Verify ref="verify" :captcha-type="'blockPuzzle'" :img-size="{ width: '400px', height: '200px' }" @success="handleRegister" />

    <el-form ref="accountRegisterForm" status-icon :model="accountRegisterForm" :rules="accountRegisterRules" auto-complete="on">
      <el-form-item prop="account">
        <el-input ref="account" v-model="accountRegisterForm.account" placeholder="账号" name="account" type="text" auto-complete="on" />
      </el-form-item>

      <el-form-item prop="password">
        <el-input ref="password" v-model="accountRegisterForm.password" placeholder="密码" name="password" type="password" auto-complete="on" />
      </el-form-item>

      <el-form-item prop="repeatPassword">
        <el-input ref="repeatPassword" v-model="accountRegisterForm.repeatPassword" placeholder="确认密码" name="repeatPassword" type="password" auto-complete="on" />
      </el-form-item>

      <el-button :loading="loading" type="primary" style="width: 100%; margin-bottom: 20px" @click.native.prevent="handleCheck"> 注 册 </el-button>
    </el-form>
  </div>
</template>

<script>
import { validateAccount, validatePassword } from '@/utils/validate.js'
import { regApi } from '@/api/api'

export default {
  name: 'RegByAccount',
  components: {
    Verify: () => import('../../components/verifition/Verify')
  },
  data() {
    const validateRepeatPassword = (rule, value, callback) => {
      if (value !== this.accountRegisterForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }

    return {
      loading: false,
      // 账号注册下表单
      accountRegisterForm: {
        account: '',
        password: '',
        repeatPassword: ''
      },
      accountRegisterRules: {
        account: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { trigger: 'blur', validator: validateAccount }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            trigger: 'blur',
            validator: validatePassword
          }
        ],
        repeatPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          {
            trigger: 'blur',
            validator: validateRepeatPassword
          }
        ]
      }
    }
  },
  methods: {
    //图片滑块验证
    handleCheck() {
      this.$refs.accountRegisterForm.validate(async (valid) => {
        if (valid) {
          this.$refs.verify.show()
        }
      })
    },
    // 注册按钮
    async handleRegister(captcha) {
      this.loading = true
      const { account, password } = this.accountRegisterForm
      const { captchaVerification } = captcha
      try {
        await this.$request(regApi.account, { account, password, captchaVerification })
        this.$message.success('注册成功,请登陆')
        this.$router.push('/login')
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    }
  }
}
</script>
